package com.whynot.frame.basic.mybatis.util;

import com.baomidou.mybatisplus.entity.TableFieldInfo;
import com.baomidou.mybatisplus.entity.TableInfo;
import com.baomidou.mybatisplus.mapper.SqlRunner;
import com.baomidou.mybatisplus.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.toolkit.TableInfoHelper;
import com.google.common.collect.Lists;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描    述:mybatis工具类
 * 创建时间: 2018/05/17
 */
public class MybatisUtil {

    private static final Logger logger = LoggerFactory.getLogger(MybatisUtil.class);


    /***
    * 描  述:不管前台传输的是属性还是字段，统一返回数据库查询统一的格式s
    * 参  数:name
    * 参  数:entity
    * 返回值: java.lang.String
    * 创建时间: 2018/5/17
    */
    public static String getColumn(String name, Class cls){
        String result=name;
        //获取全部的字段，排除参数中不属于字段的参数
        TableInfo tableInfo = TableInfoHelper.getTableInfo(ReflectionKit.getSuperClassGenricType(cls,0));
        List<TableFieldInfo> fields=tableInfo.getFieldList();
        //支持字段名和属性名查询
        Map<String,String> fieldMap=fields.stream().collect(Collectors.toMap(TableFieldInfo::getProperty, TableFieldInfo::getColumn));
        if(fieldMap.keySet().contains(name)){
            //如果传递的属性
            result=fieldMap.get(name);
        }
        return result;
    }


    /***
    * 描  述:  根据statment select 运行sql
    * 参  数:statement
    * 参  数:parameter
    * 返回值: java.util.List<java.lang.Object>
    * 创建时间: 2018/7/30
     *
    */
    public static List<Object> selectByStatement(String statement, Map<String,Object> parameter ){
        SqlSession sqlSession = null;
        List<Object>  list = Lists.newArrayList();
        try{
            sqlSession = SqlRunner.FACTORY.openSession();
            list = sqlSession.selectList(statement, parameter);
        }catch (Exception e){
            logger.error(e.getMessage());
        }finally {
            if(null != sqlSession){
                sqlSession.close();
            }
        }
        return list;
    }


    /** 
    * 描  述: 根据statment insert 运行sql
    * 参  数:statement
    * 参  数:parameter
    * 返回值: boolean 
    * 创建时间: 2018/7/30 
     *
    */
    public static boolean insertByStatement(String statement, List<Map<String,?>> parameter ){
        SqlSession sqlSession = null;
        try{
            sqlSession = SqlRunner.FACTORY.openSession();
            sqlSession.insert(statement,parameter);
            sqlSession.commit(true);
        }catch (Exception e){
            logger.error(e.getMessage());
            return false;
        }finally {
            if(null != sqlSession){
                sqlSession.close();
            }
        }
        return true;
    }

}
